<template>
  <view class="calendar">
    <view class="top-bar">
      <u-icon class="top-bar-icon" @click="turningYear('prev')" name="arrow-left-double" size="20"></u-icon>
      <u-icon class="top-bar-icon" @click="turning('prev')" name="arrow-left" size="20"></u-icon>
      <view class="top-bar-ym">{{ y }}{{ text.year }}{{ m + 1 }}{{ text.month }}</view>
      <u-icon class="top-bar-icon" @click="turning('next')" name="arrow-right" size="20"></u-icon>
      <u-icon class="top-bar-icon" @click="turningYear('next')" name="arrow-right-double" size="20"></u-icon>
    </view>

    <view class="week">
      <view class="week-day" v-for="(item, index) in weekDay" :key="index">{{ item }}</view>
    </view>

    <view :class="{ hide: !monthOpen }" class="content" :style="{ height: height }">
      <view :style="{ top: positionTop + 'upx' }" class="days">
        <view class="item" :class="{ chooseItem: choose == `${item.year}-${item.month + 1}-${item.date}` }"
          v-for="(item, index) in dates" :key="index">
          <view class="day" @click="selectOne(item, $event)"
            :class="{ choose: choose == `${item.year}-${item.month + 1}-${item.date}`, nolm: !item.lm, holiday: isHoliday(item) }">
            {{ item.date }}
          </view>
          <!-- 打卡状态点颜色控制 -->
          <view v-show="isNext(item)" :class="setDrop(item)"></view>
        </view>
      </view>
    </view>

    <view class="weektoggel">
      <view class="arrow">
        <u-icon v-if="!monthOpen" @click="trgWeek()" color="#999" name="arrow-down" size="24"></u-icon>
        <u-icon v-else @click="trgWeek()" color="#999" name="arrow-up" size="24"></u-icon>
      </view>
    </view>


  </view>
</template>

<script>
import dayjs from 'dayjs'

export default {
  name: 'attend-calendar',
  props: {
    // 第一列星期几
    weekstart: {
      type: Number,
      default: 1
    },
    // 月打卡数据
    monthData: {
      type: Array,
      default: []
    },
    // 入职日期
    staffDate: {
      type: String,
      default: ''
    },
    // 是否展开
    open: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      text: {
        year: '年',
        month: '月',
        week: ['一', '二', '三', '四', '五', '六', '日'],
        today: '今'
      },
      y: new Date().getFullYear(), // 年
      m: new Date().getMonth(), // 月
      dates: [], // 当前月日期集合
      positionTop: 0,
      monthOpen: true,
      choose: '',
      chooseIndex: null
    }
  },
  mounted () {
    let date = new Date()
    let y = date.getFullYear()
    let m = date.getMonth()
    let d = date.getDate()
    this.dates = this.monthDay(this.y, this.m)
    !this.open && this.trgWeek()
    this.choose = `${y}-${m + 1}-${d}`


  },
  computed: {
    // 顶部星期栏目
    weekDay () {
      return this.text.week.slice(this.weekstart - 1).concat(this.text.week.slice(0, this.weekstart - 1))
    },
    height () {
      return (this.dates.length / 7) * 96 + 'upx'
    }
  },
  methods: {
    isHoliday (item) {
      // 非当月
      // if (!item.index) {
      //   return true
      // }
      // const day = this.monthData[item.index];
      // if ((day && day.is_holiday && day.is_holiday == 1) || item.day == 7) {
      //   return true
      // }
    },
    setDrop (item) {
      const staffTime = dayjs(this.staffDate, 'YYYY-MM-DD').valueOf();
      const itemTime = dayjs(`${item.year}-${item.month + 1}-${item.date}`, 'YYYY-M-D').valueOf();
      const todayTime = dayjs().startOf('day').valueOf();

      // 入职前不显示
      if (staffTime > itemTime) return '';

      // 非当月不显示
      if (item.index === undefined || item.index === null) return '';

      const day = this.monthData[item.index];
      if (!day) return '';

      const isWorkday = day.is_holiday != 1 && day.week !== '周日';

      // 打卡状态
      const hasSb = !!day.sb_clock_time;
      const hasXb = !!day.xb_clock_time;
      const sbStatus = day.is_sb_status; // 1正常 2迟到/0缺卡
      const xbStatus = day.is_xb_status; // 1正常 2早退/0缺卡

      // 今天或过去日期才显示
      if (itemTime <= todayTime) {

        // 上下班都打卡且正常 → 绿色
        if (hasSb && hasXb && sbStatus === 1 && xbStatus === 1) {
          return 'drop';
        }

        // 上下班打卡异常（迟到/早退）或只打了一条 → 黄色
        if ((hasSb && hasXb && (sbStatus !== 1 || xbStatus !== 1)) ||
          (hasSb && !hasXb) || (!hasSb && hasXb)) {
          return 'drop error-drop';
        }

        // 今天要上班但未打卡 → 黄色
        if (isWorkday && !hasSb && !hasXb) {
          return 'drop error-drop';
        }

        // 非工作日且没打卡 → 不显示
        return '';
      }

      // 未来未打卡不显示
      return '';

    },
    isNext (item) {
      const today = new Date().getTime();
      const itemDate = new Date(item.year, item.month, item.date).getTime();
      return today - itemDate > 0;
    },
    // 获取当前月份天数
    monthDay (y, m) {
      let firstDayOfMonth = new Date(y, m, 1).getDay() // 当月第一天星期几
      let lastDateOfMonth = new Date(y, m + 1, 0).getDate() // 当月最后一天
      let lastDayOfLastMonth = new Date(y, m, 0).getDate() // 上一月的最后一天

      let dates = [] // 所有渲染日历
      let weekstart = this.weekstart == 7 ? 0 : this.weekstart // 方便进行日期计算，默认星期从0开始
      let startDay = (() => {
        // 周初有几天是上个月的
        if (firstDayOfMonth == weekstart) {
          return 0
        } else if (firstDayOfMonth > weekstart) {
          return firstDayOfMonth - weekstart
        } else {
          return 7 - weekstart + firstDayOfMonth
        }
      })()

      let endDay = 7 - ((startDay + lastDateOfMonth) % 7) // 结束还有几天是下个月的
      // 当一月周前几天
      for (let i = 1; i <= startDay; i++) {
        dates.push({
          date: lastDayOfLastMonth - startDay + i,
          day: weekstart + i - 1 || 7,
          month: m - 1 >= 0 ? m - 1 : 12,
          year: m - 1 >= 0 ? y : y - 1
        })
      }
      // 当月
      for (let j = 1; j <= lastDateOfMonth; j++) {
        dates.push({
          index: j - 1,
          date: j,
          day: (j % 7) + firstDayOfMonth - 1 || 7,
          month: m,
          year: y,
          lm: true,
        })
      }
      // 下一月周前几天
      for (let k = 1; k <= endDay; k++) {
        dates.push({
          date: k,
          day: (lastDateOfMonth + startDay + weekstart + k - 1) % 7 || 7,
          month: m + 1 <= 11 ? m + 1 : 0,
          year: m + 1 <= 11 ? y : y + 1
        })
      }

      return dates
    },
    isToday (y, m, d) {
      let date = new Date()
      return y == date.getFullYear() && m == date.getMonth() && d == date.getDate()
    },
    // 切换成周模式
    trgWeek () {
      this.monthOpen = !this.monthOpen
      if (this.monthOpen) {
        this.positionTop = 0
      } else {
        let index = -1
        this.dates.forEach((i, x) => {
          this.isToday(i.year, i.month, i.date) && (index = x)
        })
        this.positionTop = -((Math.ceil((index + 1) / 7) || 1) - 1) * 96
      }
    },
    // 点击回调
    selectOne (i, event) {
      // if (this.monthData[i.index].is_holiday == 1) return;

      let date = `${i.year}-${i.month + 1}-${i.date}`
      if (i.month != this.m) {
        console.log('不在可选范围内')
        return false
      }
      this.choose = date
      this.chooseIndex = i
      this.$emit('dayChange', i)
    },
    // 上个月，下个月
    turning (_action) {
      if (_action === 'next') {
        if (this.m + 1 == 12) {
          this.m = 0
          this.y = this.y + 1
        } else {
          this.m = this.m + 1
        }
      } else {
        if (this.m + 1 == 1) {
          this.m = 11
          this.y = this.y - 1
        } else {
          this.m = this.m - 1
        }
      }
      this.dates = this.monthDay(this.y, this.m)
      this.$emit('monthChange', dayjs(`${this.y}-${this.m + 1}`).format('YYYY-MM'))
    },
    // 上个年，下个年
    turningYear (_action) {
      if (_action === 'next') {
        this.y = this.y + 1
      } else {
        this.y = this.y - 1
      }
      this.dates = this.monthDay(this.y, this.m)
      this.$emit('monthChange', dayjs(`${this.y}-${this.m + 1}`).format('YYYY-MM'))
    }

  }
}
</script>

<style lang="scss" scoped>
.calendar {
  color: #000;
  font-size: 28upx;
  text-align: center;
  padding-bottom: 10upx;
  padding-top: 24rpx;
  margin-bottom: 28rpx;

  .top-bar {
    display: flex;
    justify-content: space-between;
    padding: 0 24upx;
    height: 80upx;

    &.icon {
      width: 30upx;
    }

    .top-bar-ym {
      font-size: 32upx;
      height: 80upx;
      width: 340upx;
      line-height: 80upx;
    }

    .top-change-month {
      height: 80upx;
      width: 80upx;
    }
  }

  .week {
    display: flex;
    align-items: center;
    height: 96upx;
    line-height: 96upx;

    view {
      flex: 1;
    }

    .week-day {
      font-size: 24upx;
      height: 96upx;
      line-height: 96upx;
      color: #666;
    }
  }

  .content {
    position: relative;
    overflow: hidden;
    transition: height 0.4s ease;

    .days {
      transition: top 0.3s;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      position: relative;

      // .chooseItem {
      // 	background-color: #E0F2FB !important;
      // }
      .item {
        position: relative;
        display: block;
        height: 96upx;
        line-height: 96upx;
        width: calc(100% / 7);

        .drop {
          position: absolute;
          left: 50%;
          bottom: 5upx;
          transform: translateX(-50%);
          width: 8upx;
          height: 8upx;
          // background-color: #67C23A;
          background-color: #1989FA;
          border-radius: 50%;
        }

        .error-drop {
          background-color: #ff9900 !important;
        }

        .day {
          font-style: normal;
          display: inline-block;
          vertical-align: middle;
          width: 60upx;
          height: 60upx;
          line-height: 60upx;
          overflow: hidden;
          border-radius: 50%;

          &.holiday {
            color: #999;
          }

          &.choose {
            background-color: #1989FA;
            color: #FFFFFF;
          }

          &.nolm {
            color: #fff;
            opacity: 0.3;
          }
        }

        .late {
          bottom: 0;
          left: 50%;
          font-style: normal;
          width: 12upx;
          height: 12upx;
          background: #F7B300;
          border-radius: 6upx;
          position: absolute;
          margin-left: -6upx;
          pointer-events: none;
        }

        .truancy {
          bottom: 0;
          left: 50%;
          font-style: normal;
          width: 12upx;
          height: 12upx;
          background: #FF2222;
          border-radius: 6upx;
          position: absolute;
          margin-left: -6upx;
          pointer-events: none;
        }
      }
    }
  }

  .hide {
    height: 102upx !important;
  }

  .weektoggel {
    position: relative;
    height: 50upx;

    .arrow {
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
    }
  }

  .weektoggel::after {
    position: absolute;
    top: 50%;
    left: 0;
    content: "";
    background-color: #E6E6E6;
    width: 45%;
    height: 1px;
  }

  .weektoggel::before {
    position: absolute;
    top: 50%;
    right: 0;
    content: "";
    background-color: #E6E6E6;
    width: 45%;
    height: 1px;
  }
}
</style>
